package cn.yunhe.crm.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import cn.yunhe.crm.entity.Datainfo;
import cn.yunhe.crm.service.DatainfoService;

/**
 * Controller控制层
 * @author 张旭航
 */

@Scope("prototype")
@Controller
public class DatainfoController {

	@Autowired
	@Qualifier("datainfoService")
	private DatainfoService datainfoService;

	public void setDatainfoService(DatainfoService datainfoService) {
		this.datainfoService = datainfoService;
	}

	// 显示所有资料
	@RequestMapping(value = "datainfo.do")
	public String findAllDatainfo(HttpSession session) {
		List<Datainfo> datainfo = datainfoService.findAllDatainfo();
		session.removeAttribute("datainfo");
		session.setAttribute("datainfo", datainfo);
		return "datainfo";
	}
	
	// 根据id查询资料
	@RequestMapping(value = "datainfodetail.do")
	public String datainfoDetail(HttpSession session,Integer id) {
		Datainfo data = datainfoService.getDatainfoById(id);
		session.removeAttribute("datainfo");
		session.setAttribute("data", data);
		return "datainfodetail";
	}
	
	// 跳转到添加界面
	@RequestMapping(value = "datainfoadd.do")
	public String addDatainfo() {
		return "datainfoadd";
	}
	
	//添加并重定向
	@RequestMapping(value = "adddatainfo.do",method={RequestMethod.POST})
	public String addData(Datainfo datainfo,@RequestParam("file") MultipartFile file,HttpServletRequest request) throws IOException{
		
		/*
		String path = request.getSession().getServletContext().getRealPath("file");
		FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path,file.getOriginalFilename()));
		datainfo.setUploadfile(path+file.getOriginalFilename());
		datainfoService.saveDatainfo(datainfo);
		return "redirect:/datainfo.html";*/
		
	    String path = request.getSession().getServletContext().getRealPath("/WEB-INF/file/");  
        String fileName = file.getOriginalFilename();
        File targetFile = new File(path, fileName);  
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
        try {  
        	file.transferTo(targetFile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        String idPicPath = path + File.separator + fileName;
        datainfo.setUploadfile(idPicPath);
		datainfoService.saveDatainfo(datainfo);
		return "redirect:/datainfo.do";
	}
	
	//跳转到修改页面
	@RequestMapping(value = "datainfoupdate.do")
	public String updateDatainfo(HttpSession session,Integer id) {
		Datainfo data = datainfoService.getDatainfoById(id);
		session.removeAttribute("datainfo");
		session.setAttribute("datainfo", data);
		return "datainfoupdate";
	}
	
	//修改并重定向
	@RequestMapping(value = "updatadatainfo.do",method={RequestMethod.POST})
	public String updateData(Datainfo datainfo,@RequestParam("file") MultipartFile file,HttpServletRequest request) throws IOException{
		String path = request.getSession().getServletContext().getRealPath("/WEB-INF/file/");  
        String fileName = file.getOriginalFilename();
        File targetFile = new File(path, fileName);  
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
        try {  
        	file.transferTo(targetFile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        String idPicPath = path + File.separator + fileName;
        datainfo.setUploadfile(idPicPath);
        Boolean flag = datainfoService.updateDatainfo(datainfo);
		if(flag){
			return "redirect:/datainfo.do";
		}else{
			return "datainfoupdate";
		}
	}
	
	// 删除资料
	@RequestMapping("deldatainfo.do")  
    public String delUser(Integer id){  
		Boolean flag = datainfoService.deleteDatainfo(id);
		if(flag){
			return "redirect:/datainfo.do";
		}else{
			return null;
		}
    }
	
	//下载
	@RequestMapping("download.do")
	public ResponseEntity<byte[]> download(HttpServletRequest request,HttpServletResponse response,Integer id) throws Exception{
		Datainfo data = datainfoService.getDatainfoById(id);
		String path = data.getUploadfile();
		File file = new File(path);
		HttpHeaders headers = new HttpHeaders();
		String filename = new String(file.getName().getBytes("UTF-8"),"ISO-8859-1");
		headers.setContentDispositionFormData("file", filename);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.OK);
		
	}
	
}
